package com.youlai.boot.system.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.system.mapper.PlotMapper;
import com.youlai.boot.system.model.QB.Plot;
import com.youlai.boot.system.service.PlotService;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class PlotServiceImpl extends ServiceImpl<PlotMapper, Plot>  implements PlotService {
    private static final Logger logger = LoggerFactory.getLogger(DeviceServiceImpl.class);
    @Autowired
    private PlotMapper plotMapper;
    @Override
    public boolean addPlot(Plot plot) {

        plot.setStatus(1);
        if(plot.getPicUrls() != null && !plot.getPicUrls().isEmpty()){
            String picUrl = "";
            for (String str : plot.getPicUrls()) {
                picUrl +=  str+",";
            }
            if(StringUtils.isNotBlank(picUrl)) {
                plot.setPicUrl(picUrl.substring(0,picUrl.length() -1));
            }
        }
        return save(plot);
    }

    @Override
    public List<Plot> getAllPlots() {
        return plotMapper.selectList(null);
    }

    @Override
    public Plot getPlotByNumber(String plotnumber) {
        return plotMapper.selectByPlotNumber(plotnumber);
    }

    @Override
    public boolean updatePlotStatus(String plotnumber, int newStatus) {
        Plot plot = lambdaQuery().eq(Plot::getPlotnumber,plotnumber)
                .one();
        if (plot == null){
            logger.info("未找到相应的地块编号，无法修改状态" + plotnumber);
            return false;
        }
        plot.setStatus(newStatus);
        plot.setUpdatedAt(LocalDateTime.now());
        boolean result = updateById(plot);
        if (result){
            logger.info("设备{}状态已经修改成："+plotnumber,newStatus);
        }
        else {
            logger.error("地块装填修改失败",plotnumber);
        }
        return result;
    }

    @Override
    public boolean deletePlotById(Integer id) {
        return plotMapper.deleteById(id) > 0;
    }

    @Override
    public boolean updateDevice(Plot plot) {
        if (plot ==null){
            logger.error("未查到相应设备，请重新查询");
            return false;
        }


        logger.info("尝试更新设备信息设备编号为：" + plot.getPlotnumber());
        boolean resulf = baseMapper.updateById(plot) >0;
        if (resulf){
            logger.info("设备更新成功，设备编号为：" + plot.getPlotnumber());
        }else {
            logger.warn("设备更新失败，设备编号为：" + plot.getPlotnumber());
        }
        return resulf;
    }
}
